package com.dsjy.yf.address.utils;

import com.dsjy.yf.address.entity.SplitResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author whj
 * @version 1.0
 * @date 2021-01-27 15:48
 */
@Slf4j
public class CSVUtils {
    private static final String LINE_SEPARATOR = "\r\n";

    /**
     * 临时文件存放根路径
     */
    private static final String TEMPLATE_BATH_PATH = "classpath:static/";
    /**
     * 行尾分隔符定义
     */
    private final static String NEW_LINE_SEPARATOR = ",";


    /**
     * 上传文件
     *
     * @param multipartFile multipartFile
     * @return File
     **/
    public static File uploadFile(MultipartFile multipartFile, String path) {
        path = path + multipartFile.getOriginalFilename();
        System.out.println(path);
        try {
            File file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            multipartFile.transferTo(file);
            log.info("上传文件成功,文件名===>" + multipartFile.getOriginalFilename() + ",路径===>" + file.getPath());
            return file;
        } catch (IOException e) {
            log.error("上传文件失败" + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 下载文件
     *
     * @param response response
     * @param filePath filePath
     * @param fileName fileName
     * @return boolean
     **/
    public static boolean downloadFile(HttpServletResponse response, String filePath, String fileName) {
        FileInputStream fileInputStream = null;
        BufferedInputStream bufferedInputStream = null;
        OutputStream os = null;
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        try {
            fileInputStream = new FileInputStream(filePath + "/" + fileName);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            os = response.getOutputStream();
            //MS产本头部需要插入BOM
            //如果不写入这几个字节，会导致用Excel打开时，中文显示乱码
            os.write(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF});
            byte[] buffer = new byte[1024];
            int i = bufferedInputStream.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bufferedInputStream.read(buffer);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            //关闭流
            if (os != null) {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedInputStream != null) {
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 将地址与拆分结果合成CSV行数据
     * @param result
     * @param id
     * @param address
     * @return
     */
    public static String generateCSVLine(SplitResult result, String id, String address) {
        StringBuilder builder = null;
        if (result == null) {
            return address + LINE_SEPARATOR;
        }
        builder = new StringBuilder();
        builder.append(id).append(",").append(address).append(",").append("浙江省,").append("温州市,");
        builder.append(result.getCounty() == null ? "," : result.getCounty() + ",");
        builder.append(result.getTown() == null ? "," : result.getTown() + ",");
        builder.append(result.getExclusivezone() == null ? "," : result.getExclusivezone() + ",");
        builder.append(result.getCommunity() == null ? "," : result.getCommunity() + ",");
        builder.append(result.getVillage() == null ? "," : result.getVillage() + ",");
        builder.append(result.getStreet() == null ? "," : result.getStreet() + ",");
        builder.append(result.getDoor() == null ? "," : result.getDoor() + ",");
        builder.append(result.getYardName() == null ? "," : result.getYardName() + ",");
        builder.append(result.getYardAlias() == null ? "," : result.getYardAlias() + ",");
        builder.append(result.getSubareaName() == null ? "," : result.getSubareaName() + ",");
        builder.append(result.getSubareaAlias() == null ? "," : result.getSubareaAlias() + ",");
        builder.append(result.getInternalRoad() == null ? "," : result.getInternalRoad() + ",");
        builder.append(result.getInternalDoor() == null ? "," : result.getInternalDoor() + ",");
        builder.append(result.getBuildingNum() == null ? "," : result.getBuildingNum() + ",");
        builder.append(result.getUnit() == null ? "," : result.getUnit() + ",");
        builder.append(result.getFloor() == null ? "," : result.getFloor() + ",");
        builder.append(result.getHomeNum() == null ? "," : result.getHomeNum() + ",");
        builder.append(result.getPoi() == null ? "," : result.getPoi() + ",");
        builder.append(result.getBuildingName() == null ? "," : result.getBuildingName() + ",");
        builder.append(result.getBuildingAlias() == null ? "," : result.getBuildingAlias() + ",");
        builder.append(result.getRest() == null ? "" : result.getRest());
        return builder.append(LINE_SEPARATOR).toString();
    }
}
